package com.kyleromano.disgaea;

import java.util.Random;

import com.kyleromano.disgaea.dataType.Classes;
import com.kyleromano.disgaea.dataType.ParentJob;
import com.kyleromano.disgaea.sql.CharacterDataSource;
import com.kyleromano.disgaea.sql.DBConstants;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class ClassUnlockViewActivity extends Activity {
	private CharacterDataSource db;
	private SparseArray<CheckBox> classes = new SparseArray<CheckBox>();
	private int twentyDIP;
	private int tenDIP;
	private boolean noSave = true;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.class_unlock_view);
		db = new CharacterDataSource(this);
		db.open();

		// Back to Home Screen
		Button back = (Button)this.findViewById(R.id.classUnlockViewBackButton);
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intent = new Intent();
				setResult(RESULT_OK, intent);
				finish();
			}
		});
		
		Spinner chapter = (Spinner)this.findViewById(R.id.currChapter);
		Cursor c = db.select("SELECT * FROM " + DBConstants.TCHAPTER + ";", null);
		if(c != null && c.getCount() > 0) {
			c.moveToFirst();
			int i = c.getInt(0)-1;
			if(i > 0)
				chapter.setSelection(i);
			else
				chapter.setSelection(0);
			c.close();
		}
		chapter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        	public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        		if(!noSave) {
        			ContentValues cv = new ContentValues();
        			cv.put(DBConstants.CCURRENTCHAPTER, pos+1);
        			db.update(DBConstants.TCHAPTER, cv, DBConstants.CCURRENTCHAPTER + "< 100", null);
        			checkAdvancedRequirements(ParentJob.BOUNCER);
        			checkAdvancedRequirements(ParentJob.ANDROID);
        		}
        	}
			public void onNothingSelected(AdapterView<?> arg0) {}
		});
		twentyDIP = (int) (12 * this.getResources().getDisplayMetrics().density + 0.5f);
		tenDIP = (int) (10 * this.getResources().getDisplayMetrics().density + 0.5f);

		buildMap();
		buildUI(ParentJob.WARRIOR,true);		buildUI(ParentJob.VALKYRIE,false);
		buildUI(ParentJob.WITCH,true);			buildUI(ParentJob.MAGICIAN,false);
		buildUI(ParentJob.HEALER,true);			buildUI(ParentJob.ARCHER,false);
		buildUI(ParentJob.GUNNER,true);			buildUI(ParentJob.ARMORKNIGHT,false);
		buildUI(ParentJob.THIEF,true);			buildUI(ParentJob.NINJA,false);
		buildUI(ParentJob.SAMURAI,true);		buildUI(ParentJob.BEASTMASTER,false);
		buildUI(ParentJob.SORCERER,true);		buildUI(ParentJob.BOUNCER,false);
		buildUI(ParentJob.PROFESSOR,true);		buildUI(ParentJob.MAGICKNIGHT,false);
		buildUI(ParentJob.MASKEDHERO,true);		buildUI(ParentJob.ONMYOMONK,false);
		buildUI(ParentJob.BATTLESUIT,true);		buildUI(ParentJob.ANDROID,false);
		buildUI(ParentJob.SLUDGE,true);			buildUI(ParentJob.ORC,false);
		buildUI(ParentJob.MOTHMAN,true);		buildUI(ParentJob.SHROOM,false);
		buildUI(ParentJob.GHOST,true);			buildUI(ParentJob.SLUMBERCAT,false);
		buildUI(ParentJob.PRINNY,true);			buildUI(ParentJob.ZOMBIE,false);
		buildUI(ParentJob.GARGOYLE,true);		buildUI(ParentJob.FLORABEAST,false);
		buildUI(ParentJob.ROC,true);			buildUI(ParentJob.REAPER,false);
		buildUI(ParentJob.MYSTICBEAST,true);	buildUI(ParentJob.SUCCUBUS,false);
		buildUI(ParentJob.DRAGONZOMBIE,true);	buildUI(ParentJob.WOODGOLEM,false);
		buildUI(ParentJob.DRAGON,true);			buildUI(ParentJob.FELYNN,false);
		buildUI(ParentJob.RIFLEDEMON,true);

		unlockClasses();
		new CheckRequirementsThread(this).execute();
		//checkBasicRequirements();
		/*
		 * ARMORKNIGHT	= Warrior 20									***Handled***
		 * MAGICKNIGHT	= Warrior 30, Skull 30 OR Valkyrie 30, Mage 30	***Handled***
		 * 
		 * ARCHER		= Healer 15, Valkyrie 15						***Handled***
		 * GUNNER		= Thief 15, Skull 15							***Handled***
		 * NINJA		= Thief 30, Skull 30							***Handled***
		 * SAMURAI		= Valkyrie 30, Archer 30						***Handled***
		 * BEASTMASTER	= Warrior 15, Valkyrie 15						***Handled***
		 * SORCERER		= Skull 15, Witch 15							***Handled***
		 * PROFESSOR	= Healer 20, Onmyo 20							***Handled***
		 * MASKEDHERO	= Thief 25, Warrior 25							***Handled***
		 * ONMYOMONK	= Sorcerer 30, Ninja 30							***Handled***
		 * BIOSUIT		= Warrior 30, Armor Knight 30					***Handled***
		 * 
		 * ANDROID		= Beat Game, Start 2nd Cycle					***Handled***
		 * BOUNCER		= Complete Episode 8							***Handled***
		 */
		//checkAdvancedRequirements();
	}

	@Override
	public void onPause()
	{
		super.onPause();
		db.close();
	}
	@Override
	public void onResume()
	{
		super.onResume();
		db.open();
		new CheckRequirementsThread(this).execute();
		//checkBasicRequirements();
		//checkAdvancedRequirements();
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		db.close();
	}
	
	/**
	 * Check two tier requirements
	 * @param jobID1 First job tier involved in the requirements
	 * @param jobID2 Second job tier involved in the requirements
	 * @param unlockClassID The class we're attempting to unlock
	 */
	private void checkAdvancedRequirements(int unlockClassID) {
		CheckBox cb = null;
		if(unlockClassID == Classes.BOUNCER) {
			Spinner chapter = (Spinner)this.findViewById(R.id.currChapter);
			if(chapter.getSelectedItemPosition() + 1 > 8) {
				cb = classes.get(unlockClassID);
				cb.setChecked(true);
			}
		} else if(unlockClassID == Classes.ANDROID) {
			Spinner chapter = (Spinner)this.findViewById(R.id.currChapter);
			if(chapter.getSelectedItemPosition() + 1 == 11) {
				cb = classes.get(unlockClassID);
				cb.setChecked(true);
			}
		}
	}
	
	/**
	 * Need to generate a header for each job and 6 checkboxes for each class associated
	 * Store the classes as an array in a known order for easy iteration in other methods
	 * This function is going to be massive and annoying to maintain
	 */
	private void buildMap()
	{
		Resources r = getResources();
		putClassInHashMap(ParentJob.WARRIOR, r.getStringArray(R.array.maleFighter));
		putClassInHashMap(ParentJob.VALKYRIE, r.getStringArray(R.array.femaleFighter));
		putClassInHashMap(ParentJob.WITCH,r.getStringArray(R.array.mage));
		putClassInHashMap(ParentJob.MAGICIAN,r.getStringArray(R.array.skull));
		putClassInHashMap(ParentJob.HEALER,r.getStringArray(R.array.healer));
		putClassInHashMap(ParentJob.ARCHER,r.getStringArray(R.array.archer));
		putClassInHashMap(ParentJob.GUNNER,r.getStringArray(R.array.gunner));
		putClassInHashMap(ParentJob.ARMORKNIGHT,r.getStringArray(R.array.armorKnight));
		putClassInHashMap(ParentJob.THIEF,r.getStringArray(R.array.thief));
		putClassInHashMap(ParentJob.NINJA,r.getStringArray(R.array.ninja));
		putClassInHashMap(ParentJob.SAMURAI,r.getStringArray(R.array.samurai));
		putClassInHashMap(ParentJob.BEASTMASTER,r.getStringArray(R.array.beastMaster));
		putClassInHashMap(ParentJob.SORCERER,r.getStringArray(R.array.sorcerer));
		putClassInHashMap(ParentJob.BOUNCER,r.getStringArray(R.array.bouncer));
		putClassInHashMap(ParentJob.PROFESSOR,r.getStringArray(R.array.professor));
		putClassInHashMap(ParentJob.MAGICKNIGHT,r.getStringArray(R.array.magicKnight));
		putClassInHashMap(ParentJob.MASKEDHERO,r.getStringArray(R.array.maskedHero));
		putClassInHashMap(ParentJob.ONMYOMONK,r.getStringArray(R.array.onmyoMonk));
		putClassInHashMap(ParentJob.BATTLESUIT,r.getStringArray(R.array.battleSuit));
		putClassInHashMap(ParentJob.ANDROID,r.getStringArray(R.array.android));
		putClassInHashMap(ParentJob.SLUDGE,r.getStringArray(R.array.sludge));
		putClassInHashMap(ParentJob.ORC,r.getStringArray(R.array.orc));
		putClassInHashMap(ParentJob.MOTHMAN,r.getStringArray(R.array.mothman));
		putClassInHashMap(ParentJob.SHROOM,r.getStringArray(R.array.shroom));
		putClassInHashMap(ParentJob.GHOST,r.getStringArray(R.array.ghost));
		putClassInHashMap(ParentJob.SLUMBERCAT,r.getStringArray(R.array.slumberCat));
		putClassInHashMap(ParentJob.PRINNY,r.getStringArray(R.array.prinny));
		putClassInHashMap(ParentJob.ZOMBIE,r.getStringArray(R.array.zombie));
		putClassInHashMap(ParentJob.GARGOYLE,r.getStringArray(R.array.gargoyle));
		putClassInHashMap(ParentJob.FLORABEAST,r.getStringArray(R.array.floraBeast));
		putClassInHashMap(ParentJob.ROC,r.getStringArray(R.array.roc));
		putClassInHashMap(ParentJob.REAPER,r.getStringArray(R.array.reaper));
		putClassInHashMap(ParentJob.MYSTICBEAST,r.getStringArray(R.array.mysticBeast));
		putClassInHashMap(ParentJob.SUCCUBUS,r.getStringArray(R.array.succubus));
		putClassInHashMap(ParentJob.DRAGONZOMBIE,r.getStringArray(R.array.dragonZombie));
		putClassInHashMap(ParentJob.WOODGOLEM,r.getStringArray(R.array.woodGolem));
		putClassInHashMap(ParentJob.DRAGON,r.getStringArray(R.array.dragon));
		putClassInHashMap(ParentJob.FELYNN,r.getStringArray(R.array.felynn));
		putClassInHashMap(ParentJob.RIFLEDEMON,r.getStringArray(R.array.rifleDemon));
	}

	private void putClassInHashMap(int classID, String[] collection)
	{
		for(int i = 0; i < 6; i++)
		{
			CheckBox c = new CheckBox(this);
			c.setText(collection[i]);
			c.setTextSize(12);
			c.setId(classID+i);
			c.setButtonDrawable(R.drawable.btn_check_simple);
			c.setMinHeight(tenDIP);
			c.setMinimumHeight(tenDIP);
			//LayoutParams p = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			//c.setLayoutParams(p);
			//c.setPadding(0, 10, 0, 10);
			c.setOnCheckedChangeListener(new OnCheckedChangeListener(){
				public void onCheckedChanged(CompoundButton checkBox, boolean checked) {
					int classID = checkBox.getId();

					//Confirm that we're not trying to uncheck a permanently unlocked class
					if(!checked) {
						//This feels like the worst possible way to check for this condition...
						if( classID == Classes.FIGHTER    || classID == Classes.LADYFIGHTER   || classID == Classes.REDSKULL   ||
								classID == Classes.GREENSKULL || classID == Classes.BLUESKULL     || classID == Classes.REDMAGE    ||
								classID == Classes.GREENMAGE  || classID == Classes.BLUEMAGE      || classID == Classes.HEALER     ||
								classID == Classes.THIEF      || classID == Classes.GREENSLIME    || classID == Classes.PETITEORC  ||
								classID == Classes.MOTHMAN    || classID == Classes.ERYNGI        || classID == Classes.GHOST      ||
								classID == Classes.CATSABER   || classID == Classes.PRIVATEPRINNY || classID == Classes.ZOMBIE     ||
								classID == Classes.GARGOYLE   || classID == Classes.ALRAUNE       || classID == Classes.COCKATRICE ||
								classID == Classes.CUSITH) {
							checkBox.setChecked(true);
							return;
							//And that we're not trying to uncheck the middle of a list
						} else if(classes.get((classID+1)) != null && classes.get(classID+1).isChecked()) {
							checkBox.setChecked(true);
							return;
						}
					}
					if(checkBox.isEnabled()) {
						ContentValues cv;
						CheckBox prev = classes.get((classID-1));
						CheckBox next = classes.get((classID+1));
						if(prev == null ||
								(prev.isChecked() && next == null) ||
								(prev.isChecked() && !next.isChecked())) {
							if(checked && !noSave) {
								cv = new ContentValues();
								cv.put(DBConstants.CCLASSUNLOCKED, 1);
								db.update(DBConstants.TCLASSES, cv, DBConstants.CCLASSID+ "=?", new String[]{classID + ""});
							} else if(!checked && !noSave) {
								cv = new ContentValues();
								cv.put(DBConstants.CCLASSUNLOCKED, 0);
								db.update(DBConstants.TCLASSES, cv, DBConstants.CCLASSID+ "=?", new String[]{classID + ""});
							}
						} else {
							//potential for infinite loop?
							checkBox.setChecked(!checked);
						}
					}
				}
			}
					);
			classes.put((classID + i), c);
		}
	}

	/**
	 * Construct the UI from the data in the hash
	 */
	private void buildUI(int classID, boolean leftColumn)
	{
		//Should I build in the left column or the right column?
		if(leftColumn) {
			LinearLayout left = (LinearLayout) findViewById(R.id.classUnlockViewLeftPanel);
			TextView t = new TextView(this);
			t.setText(getString(Classes.getClassNameResID(classID)));
			t.setTextColor(Color.parseColor("#FFBA00"));
			t.setTextSize(twentyDIP);
			left.addView(t);
			for(int i = 0; i < 6; i++) {
				left.addView(classes.get(classID + i));
			}
		} else {
			LinearLayout right = (LinearLayout) findViewById(R.id.classUnlockViewRightPanel);
			TextView t = new TextView(this);
			t.setText(getString(Classes.getClassNameResID(classID)));
			t.setTextColor(Color.parseColor("#FFBA00"));
			t.setTextSize(twentyDIP);
			right.addView(t);
			for(int i = 0; i < 6; i++) {
				right.addView(classes.get(classID + i));
			}
		}
	}

	/**
	 * read the database for unlocked class entries and update checkboxes accordingly
	 */
	private void unlockClasses()
	{
		CheckBox c;
		Cursor v = db.getUnlockedClasses();
		if(v == null)
			return;
		while(v.moveToNext())
		{
			//DB Connection
			//get checkbox that matches the class ID returned by the database
			c = classes.get(v.getInt(0));
			//if db value is unlocked check the box
			if(c != null && !c.isChecked())
				c.setChecked(true);
		}
		noSave = false;
	}
	
	/**************************************************************************
	 * Thread requirements check to reduce load time and ensure accurate results
	 * @author kromano
	 *
	 **************************************************************************/
	private class CheckRequirementsThread extends AsyncTask<Void, Void, Void> {
		private ProgressDialog loadingBar;
		private Context context;
		
		private CheckRequirementsThread(Context context) {
			this.context = context;
		}

		@Override
		protected Void doInBackground(Void... params) {
			checkBasicRequirements();
			checkAdvancedRequirements();
			return null;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			String[] loadingStrings = getResources().getStringArray(R.array.aLoadingStrings);
			// Show a Spinner progressDialog
    		loadingBar = new ProgressDialog(context, ProgressDialog.STYLE_SPINNER);
    		loadingBar.setTitle(loadingStrings[new Random().nextInt(loadingStrings.length)]);
    		loadingBar.show();
		}
		
		@Override
		protected void onPostExecute(Void v) {
			loadingBar.dismiss();
		}
		/**
		 * read saved character data to determine which classes should be unlocked automatically
		 */
		private void checkBasicRequirements()
		{
			//some DB connection which tests a bunch of conditions and sets the unlocked value
			String select = "SELECT " + DBConstants.CCLASSID + ", MAX(" + DBConstants.CLEVEL + ") as level FROM " +
					DBConstants.VCHARACTER + " GROUP BY " + DBConstants.CCLASSID + ";";
			Cursor c = db.select(select, null);
			int currentID = -1;
			int currentLevel = -1;
			int levelRequirement = -1;
			CheckBox cb;
			if(c != null && c.getCount() > 0) {
				while(c.moveToNext()){
					cb = null;
					currentID = c.getInt(0);
					currentLevel = c.getInt(1);
					levelRequirement = Classes.getUpgradeRequirement(currentID);
					//If the level requirement is returned less than 0 it is a special case, otherwise do a basic level comparison check
					if(levelRequirement > 0) {
						if(currentLevel >= levelRequirement) {
							//We should probably check that the preceeding tier is unlocked before making assumptions and winding up in impossible situations
							//if(Classes.getUpgradeRequirement(currentID - 1) > 0)
							cb = classes.get(currentID - 1);
							//if cb is null this is the first tier in the list so it's safe to unlock the next tier,
							//otherwise make sure the previous tier has been unlocked to avoid getting stuck
							if(cb == null || cb.isChecked())
								//It's safe to unlock the next tier
								classes.get(currentID + 1).setChecked(true);
						}
						//-1 defines no next tier to unlock
					} else if(levelRequirement == -2) {
						//It's a mage!
						int mage1 = -1;
						int mage2 = -1;
						int mage3 = -1;
						//get the levels of the three required classes, either Skull or Mage
						if(currentID == Classes.REDMAGE || currentID == Classes.GREENMAGE || currentID == Classes.BLUEMAGE) {
							mage1 = getClassLevelFromCursor(Classes.REDMAGE, c);
							mage2 = getClassLevelFromCursor(Classes.GREENMAGE, c);
							mage3 = getClassLevelFromCursor(Classes.BLUEMAGE, c);
						} else if(currentID == Classes.REDSKULL || currentID == Classes.GREENSKULL || currentID == Classes.BLUESKULL) {
							mage1 = getClassLevelFromCursor(Classes.REDSKULL, c);
							mage2 = getClassLevelFromCursor(Classes.GREENSKULL, c);
							mage3 = getClassLevelFromCursor(Classes.BLUESKULL, c);
						}
						//Check to make sure that all three values have been initialized otherwise requirements aren't met
						if(mage1 > 0 && mage2 > 0 && mage3 > 0)
							//Check the total of all three is greater than or equal to 50 and unlock the next tier if true
							if( (mage1 + mage2 + mage3) >= 50 )
								classes.get(currentID + 1).setChecked(true);
					}
				}
				//we're finished with the cursor object
				c.close();
			}
		}

		/**
		 * Bulk check all job requirements
		 */
		private void checkAdvancedRequirements() {
			checkAdvancedRequirements(0, 0, Classes.HEAVYKNIGHT);
			checkAdvancedRequirements(0, 0, Classes.MAGICKNIGHT);
			checkAdvancedRequirements(ParentJob.HEALER, ParentJob.VALKYRIE, Classes.ARCHER);
			checkAdvancedRequirements(ParentJob.THIEF, ParentJob.MAGICIAN, Classes.GUNNER);
			checkAdvancedRequirements(ParentJob.THIEF, ParentJob.MAGICIAN, Classes.GENIN);
			checkAdvancedRequirements(ParentJob.VALKYRIE, ParentJob.ARCHER, Classes.EXORCIST);
			checkAdvancedRequirements(ParentJob.WARRIOR, ParentJob.VALKYRIE, Classes.BEASTTAMER);
			checkAdvancedRequirements(ParentJob.MAGICIAN, ParentJob.WITCH, Classes.SHAMAN);
			checkAdvancedRequirements(ParentJob.HEALER, ParentJob.ONMYOMONK, Classes.PROFESSOR);
			checkAdvancedRequirements(ParentJob.THIEF, ParentJob.WARRIOR, Classes.MASKEDHERO);
			checkAdvancedRequirements(ParentJob.SORCERER, ParentJob.NINJA, Classes.ONMYOTRAINEE);
			checkAdvancedRequirements(ParentJob.WARRIOR, ParentJob.ARMORKNIGHT, Classes.BIOSUIT);
		}

		/**
		 * Check two tier requirements
		 * @param jobID1 First job tier involved in the requirements
		 * @param jobID2 Second job tier involved in the requirements
		 * @param unlockClassID The class we're attempting to unlock
		 */
		private void checkAdvancedRequirements(int jobID1, int jobID2, int unlockClassID) {
			String select = null;
			Cursor c = null;
			int class1Level = -1;
			int class2Level = -1;
			CheckBox cb = null;
			if(unlockClassID == Classes.HEAVYKNIGHT)
			{
				select = "SELECT " + DBConstants.CJOBID + ", MAX(" + DBConstants.CLEVEL + ") as level FROM " + DBConstants.VCHARACTER +
						" WHERE " + DBConstants.CJOBID + "=" + ParentJob.WARRIOR +
						" GROUP BY " + DBConstants.CJOBID + ";";
				c = db.select(select, null);			
				if(c != null && c.getCount() > 0)
					if(c.moveToNext())
						class1Level = c.getInt(0);
				if(class1Level >= 20) {
					cb = classes.get(unlockClassID);
					cb.setChecked(true);
				}
			} else if(unlockClassID == Classes.MAGICKNIGHT)	{
				select = "SELECT " + DBConstants.CJOBID + ", MAX(" + DBConstants.CLEVEL + ") as level FROM " + DBConstants.VCHARACTER +
						" WHERE " + DBConstants.CJOBID + "=" + ParentJob.WARRIOR +
						" OR " + DBConstants.CJOBID + "=" + ParentJob.MAGICIAN +
						" GROUP BY " + DBConstants.CJOBID + ";";
				c = db.select(select,  null);
				if(c != null && c.getCount() > 1) {
					if(c.moveToNext())
						class1Level = c.getInt(0);
					if(c.moveToNext())
						class2Level = c.getInt(0);
					if(class1Level >= 30 && class2Level >= 30) {
						cb = classes.get(unlockClassID);
						cb.setChecked(true);
					}
				} else {
					select = "SELECT " + DBConstants.CJOBID + ", MAX(" + DBConstants.CLEVEL + ") as level FROM " + DBConstants.VCHARACTER +
							" WHERE " + DBConstants.CJOBID + "=" + ParentJob.VALKYRIE +
							" OR " + DBConstants.CJOBID + "=" + ParentJob.WITCH +
							" GROUP BY " + DBConstants.CJOBID + ";";
					c = db.select(select,  null);
					if(c != null && c.getCount() > 1) {
						if(c.moveToNext())
							class1Level = c.getInt(0);
						if(c.moveToNext())
							class2Level = c.getInt(0);
						if(class1Level >= 30 && class2Level >= 30) {
							cb = classes.get(unlockClassID);
							cb.setChecked(true);
						}
					}
				}
			} else {
				select = "SELECT " + DBConstants.CJOBID + ", MAX(" + DBConstants.CLEVEL + ") as level FROM " + DBConstants.VCHARACTER +
						" WHERE " + DBConstants.CJOBID + "=" + jobID1 +
						" OR " + DBConstants.CJOBID + "=" + jobID2 +
						" GROUP BY " + DBConstants.CJOBID + ";";
				c = db.select(select, null);			
				if(c != null && c.getCount() > 1) {
					if(c.moveToNext())
						class1Level = c.getInt(0);
					if(c.moveToNext())
						class2Level = c.getInt(0);
				}
				switch (unlockClassID) {
				case Classes.ARCHER :
				case Classes.GUNNER :
				case Classes.BEASTMASTER :
				case Classes.SHAMAN :
					if(class1Level >= 15 && class2Level >= 15) {
						cb = classes.get(unlockClassID);
						cb.setChecked(true);
					}
					break;

				case Classes.PROFESSOR :
					if(class1Level >= 20 && class2Level >= 20) {
						cb = classes.get(unlockClassID);
						cb.setChecked(true);
					}
					break;

				case Classes.MASKEDHERO :
					if(class1Level >= 25 && class2Level >= 25) {
						cb = classes.get(unlockClassID);
						cb.setChecked(true);
					}
					break;

				case Classes.GENIN :
				case Classes.ONMYOTRAINEE :
				case Classes.BIOSUIT :
				case Classes.EXORCIST :
					if(class1Level >= 30 && class2Level >= 30) {
						cb = classes.get(unlockClassID);
						cb.setChecked(true);
					}
					break;
				}
			}
			if(c != null && !c.isClosed())
				c.close();
		}

		private int getClassLevelFromCursor(int classID, Cursor c) {
			int currentPosition = c.getPosition();
			//c.moveToFirst();
			c.moveToPosition(-1);
			boolean found = false;
			int level = -1;
			while(c.moveToNext() && !found)
			{
				if(c.getInt(0) == classID) {
					level = c.getInt(1);
					found = true;
				}
			}

			c.moveToPosition(currentPosition);
			return level;
		}
	}
}